package com.belazy.basics.auth.controller;

import com.belazy.basics.auth.model.from.LoginFrom;
import com.belazy.basics.auth.model.vo.LoginVo;
import com.belazy.basics.auth.service.IAuthService;
import com.belazy.library.model.Result;
import com.belazy.library.model.constant.RedisConstant;
import com.belazy.library.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author tangcp
 */
@Slf4j
@Api(tags = "认证相关")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthController {
    private final RedisService redisService;
    private final IAuthService iAuthService;

    @GetMapping("/sendLoginSmsCode")
    @ApiOperation(value = "发送登录短信验证码")
    public Result<Boolean> sendSmsCode(@ApiParam("手机号码") @RequestParam("moible") String moible) {
        Object obj = redisService.get (RedisConstant.LOGIN_SMS_CODE_KEY + moible);
        if (!StringUtils.isEmpty (obj)) {
            return Result.fail ("已发送短信验证码，请稍后再试!");
        }
        //TODO 调用发送短信接口
        redisService.set (RedisConstant.LOGIN_SMS_CODE_KEY + moible, "123456", RedisConstant.LOGIN_SMS_CODE_EXPIRE);
        return Result.success (true);
    }

    @DeleteMapping("/logout")
    @ApiOperation(value = "登出接口")
    public Result<Boolean> logout(HttpServletRequest request) {
        String token = request.getHeader (HttpHeaders.AUTHORIZATION);
        if(StringUtils.isEmpty (token)){
            return Result.fail ("Authorization is not find!");
        }
        String tokenValue = token.split (" ")[1];
        return iAuthService.logout (tokenValue);
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录接口", response = LoginVo.class)
    public Result<LoginVo> login(@RequestBody LoginFrom from) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()).getRequest ();
        return iAuthService.login (from, request);
    }
}
